package com.briup.jdbc.execute;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class SelectExecute<T> extends AbstractExecute {

	// contains which need to select attrs
	// 存放要查询的列名
	private List<String> paramStrings;

	public SelectExecute() {
		super();
	}

	public SelectExecute(String sql, Class param, Object[] params) {
		super(sql, param, params);
	}

	public SelectExecute(String sql, Class param) {
		super(sql, param);
	}

	// 主要方法
	public List<T> select(Connection conn) throws Exception {
		analyseSelectSql(sql);
		List<Object> list = null;
		try {

			PreparedStatement ps = conn.prepareStatement(sql);
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					ps.setObject(i + 1, params[i]);
				}
			}
			ResultSet resultSet = ps.executeQuery();
			list = new ArrayList<>();
			while (resultSet.next()) {
				Object newInstance = param.newInstance();
				for (String attrName : paramStrings) {
					Field field = param.getDeclaredField(attrName);
					field.setAccessible(true);
					field.set(newInstance, resultSet.getObject(attrName));
				}
				list.add(newInstance);
			}
		} catch (Exception e) {
			throw e;
		}
		return (List<T>) list;
	}

	// 解析DQL语句,解析出查询的类名
	private void analyseSelectSql(String sql) throws Exception {
		// select param1,param2 from table.name where p1=#{p1} or/and p2=#{p2}
		if (sql == null) {
			throw new Exception("sql is null !");
		}
		if (!sql.startsWith("select")) {
			throw new Exception("sql must start with select !");
		}
		String substring = sql.substring(6, sql.indexOf("from")).replaceAll(" ", "");
		String[] split = substring.split(",");
		paramStrings = new ArrayList<String>();
		for (String string : split) {
			paramStrings.add(string);
		}
	}

}
